package com.wfy.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Title: UploadService
 * @Package com.wfy.service
 * @Author 王飞遥
 * @Date 2022/8/18 21:06
 */
@Service
public class UploadService {
    @Autowired
    FastFileStorageClient fastFileStorageClient;
    @Value("${imagesUrl}")
    private String baseUrl;
    public static  final List<String> CONTENT_TYPES= Arrays.asList("image/jpeg","image/jpg","image/png","image/gif");
    //日志  输出到文件当中
    private static  final Logger logger= LoggerFactory.getLogger(UploadService.class);
    public String upload(MultipartFile file) {
        /**
         * 校验文件大小(在application.yml处理了)
         * 校验文件的媒体类型
         * 校验文件的内容
         */
        //校验文件的媒体类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if(!CONTENT_TYPES.contains(contentType)){
            logger.info("文件类型不合法:{}",originalFilename);
            return null;
        }
        //校验文件的内容
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if(read==null){
                logger.info("文件内容不合法:{}",originalFilename);
                return null;
            }
            //保存服务器
            //file.transferTo(new File("C:\\Users\\DELL\\Pictures\\Camera Roll"));
            //获取一下图片的后缀名
            String last = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), last, null);

            //生成完整路径
            return baseUrl+storePath.getFullPath();
        } catch (IOException e) {
            logger.info("服务器内部错误:{}",originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}
